<template>
    <div class="goods-type-container">
        <!-- 查询表单 -->
        <el-card shadow="never" class="search-card">
            <el-form :model="searchForm" label-width="100px" size="medium">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="分类名称">
                            <el-input v-model="searchForm.categoryName" placeholder="请输入分类名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="分类级别">
                            <el-select v-model="searchForm.level" placeholder="请选择分类级别" clearable>
                                <el-option label="一级分类" value="一级"></el-option>
                                <el-option label="二级分类" value="二级"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="状态">
                            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                                <el-option label="启用" :value="1"></el-option>
                                <el-option label="停用" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20" class="button-group">
                        <el-button type="primary" @click="handleSearch">查询</el-button>
                        <el-button @click="resetSearch">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 分类列表 -->
        <el-card shadow="never" class="table-card">
            <div class="table-header" style="text-align: end;">
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增分类</el-button>
            </div>

            <el-table :data="tableData" border style="width: 100%" v-loading="loading">
                <!-- 添加ID列 -->
                <el-table-column prop="id" label="分类ID" width="120">
                    <template slot-scope="scope">
                        {{ scope.row.level === '一级' ? scope.row.typeFirstId : scope.row.typeSecondId }}
                    </template>
                </el-table-column>

                <el-table-column prop="categoryName" label="分类名称" width="300"></el-table-column>
                <el-table-column prop="level" label="级别" width="200"></el-table-column>
                <el-table-column prop="parentName" label="父级分类" width="300"></el-table-column>
                <el-table-column label="状态" width="150">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                            {{ scope.row.status === 1 ? '启用' : '停用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="360" fixed="right">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="mini" :type="scope.row.status === 1 ? 'danger' : 'success'"
                            @click="handleStatusChange(scope.row)">
                            {{ scope.row.status === 1 ? '停用' : '启用' }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>


            <!-- 分页 -->
            <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="pagination.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
            </el-pagination>
        </el-card>

        <!-- 新增分类弹窗 -->
        <el-dialog title="新增分类" :visible.sync="addDialogVisible" width="50%" @close="resetAddForm">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="分类名称" prop="categoryName">
                            <el-input v-model="addForm.categoryName" placeholder="请输入分类名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="分类级别" prop="level">
                            <el-select v-model="addForm.level" placeholder="请选择分类级别" style="width: 100%"
                                @change="handleLevelChange">
                                <el-option label="一级分类" value="一级"></el-option>
                                <el-option label="二级分类" value="二级"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20" v-if="addForm.level === '二级'">
                    <el-col :span="24">
                        <el-form-item label="父级分类" prop="parentId">
                            <el-select v-model="addForm.parentId" placeholder="请选择父级分类" style="width: 100%" clearable>
                                <el-option v-for="item in parentCategoryOptions" :key="item.id"
                                    :label="item.categoryName" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="addForm.status" placeholder="请选择状态" style="width: 100%">
                                <el-option label="启用" :value="1" disabled=true></el-option>
                                <el-option label="停用" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitAddForm">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑分类弹窗 -->
        <el-dialog :title="editDialogTitle" :visible.sync="editDialogVisible" width="50%" @close="resetEditForm">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="分类名称" prop="categoryName">
                            <el-input v-model="editForm.categoryName" placeholder="请输入分类名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="分类级别" prop="level">
                            <el-select v-model="editForm.level" placeholder="请选择分类级别" style="width: 100%"
                                :disabled="true">
                                <!-- 分类级别不可编辑 -->
                                <el-option label="一级分类" value="一级"></el-option>
                                <el-option label="二级分类" value="二级"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20" v-if="editForm.level === '二级'">
                    <el-col :span="24">
                        <el-form-item label="父级分类" prop="parentId">
                            <!-- 关键修改：确保v-model绑定到editForm.parentId -->
                            <el-select v-model="editForm.parentId" placeholder="请选择父级分类" style="width: 100%">
                                <el-option v-for="item in parentCategoryOptions" :key="item.id"
                                    :label="item.categoryName" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="editForm.status" placeholder="请选择状态" style="width: 100%" 
                            :disabled="true">
                                <el-option label="启用" :value="1"></el-option>
                                <el-option label="停用" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitEditForm">保 存</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
export default {
    name: 'GoodsTypeList',
    data() {
        return {
            loading: false,
            searchForm: {
                categoryName: '',
                level: null,
                status: null
            },
            tableData: [],
            pagination: {
                pageNum: 1,
                pageSize: 20,
                total: 0
            },
            // 新增分类相关数据
            addDialogVisible: false,
            addForm: {
                categoryName: '',
                level: '一级',
                parentId: null,
                typeFirstId: null,
                status: 0,
                icon: ''
            },
            addFormRules: {
                categoryName: [
                    { required: true, message: '请输入分类名称', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
                ],
                level: [
                    { required: true, message: '请选择分类级别', trigger: 'change' }
                ],
                parentId: [
                    { required: true, message: '请选择父级分类', trigger: 'change' }
                ],
                status: [
                    { required: false, message: '请选择状态', trigger: 'change' }
                ]
            },
            fileList: [],
            parentCategoryOptions: [], // 父级分类选项

            // 编辑分类相关数据
            editDialogVisible: false,
            editDialogTitle: '编辑分类',
            editForm: {
                id: null,
                categoryName: '',
                level: '',
                parentId: null,
                typeFirstId: null,
                status: 1
            },
            editFormRules: {
                categoryName: [
                    { required: true, message: '请输入分类名称', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
                ],
                status: [
                    { required: true, message: '请选择状态', trigger: 'change' }
                ]
            },
        }
    },
    created() {
        this.fetchData()
        this.fetchParentCategories()
    },
    methods: {
        // 获取分类列表数据
        async fetchData() {
            this.loading = true
            try {
                const params = {
                    pageNum: this.pagination.pageNum,
                    pageSize: this.pagination.pageSize,
                    param: {
                        ...this.searchForm,

                        // // 根据级别设置不同的参数
                        // level: this.addForm.level === '一级' ? 1 : 2
                    }
                }

                // 删除空值参数
                Object.keys(params.param).forEach(key => {
                    if (params.param[key] === null || params.param[key] === '' || params.param[key] === undefined) {
                        delete params.param[key]
                    }
                })

                this.$axios.post('api/goods/queryGoodsType', params).then(response => {
                    if (response.data.code == 200) {
                        this.tableData = response.data.data.list
                        this.pagination.total = response.data.data.total
                    } else {
                        this.$message.error(response.data.msg || '获取数据失败')
                    }
                })

            } catch (error) {
                console.error('请求出错:', error)
                this.$message.error('请求数据失败，请稍后重试')
            } finally {
                this.loading = false
            }
        },

        // 获取父级分类选项
        fetchParentCategories() {
            this.$axios.get('api/goods/queryGoodsTypeByFirst')
                .then(response => {
                    if (response.data.code === 200) {
                        // 处理返回数据，提取一级分类
                        const rawData = response.data.data;

                        // 使用Set去重
                        const uniqueFirstCategories = new Set();

                        // 遍历数据提取一级分类
                        rawData.forEach(item => {
                            if (item.typeFirstId && item.nameFirst) {
                                uniqueFirstCategories.add({
                                    id: item.typeFirstId,
                                    categoryName: item.nameFirst
                                });
                            }
                        });

                        // 转换为数组并排序
                        this.parentCategoryOptions = Array.from(uniqueFirstCategories).sort((a, b) => {
                            return a.id - b.id; // 按ID排序
                            // 或者按名称排序: return a.categoryName.localeCompare(b.categoryName);
                        });
                    }
                })
                .catch(error => {
                    console.error('获取父级分类出错:', error);
                    this.$message.error('获取父级分类失败');
                });
        },

        // 查询
        handleSearch() {
            this.pagination.pageNum = 1
            this.fetchData()
        },

        // 重置查询条件
        resetSearch() {
            this.searchForm = {
                categoryName: '',
                level: null,
                status: null
            }
            this.handleSearch()
        },

        // 分页大小变化
        handleSizeChange(val) {
            this.pagination.pageSize = val
            this.pagination.pageNum = 1
            this.fetchData()
        },

        // 当前页变化
        handleCurrentChange(val) {
            this.pagination.pageNum = val
            this.fetchData()
        },

        // 新增分类
        handleAdd() {
            this.addDialogVisible = true
        },

        // 重置新增表单
        resetAddForm() {
            this.$refs.addFormRef?.resetFields()
            this.addForm = {
                categoryName: '',
                level: '一级',
                parentId: null,
                typeFirstId: null,
                status: 0,
                icon: ''
            }
            this.fileList = []
        },

        // 分类级别变化处理
        handleLevelChange(val) {
            if (val === '一级') {
                this.addForm.parentId = null,
                    this.addForm.typeFirstId = null
            }
        },

        // 提交新增表单
        submitAddForm() {
            this.$refs.addFormRef.validate(valid => {
                if (valid) {
                    const params = {
                        ...this.addForm,
                        // 根据级别设置不同的参数
                        level: this.addForm.level === '一级' ? 1 : 2,
                        parentId: this.addForm.level === '一级' ? 0 : this.addForm.parentId,
                        typeFirstId: this.addForm.level === '一级' ? 0 : this.addForm.parentId
                    }

                    this.loading = true
                    this.$axios.post('api/goods/addGoodsType', params)
                        .then(response => {
                            if (response.data.code === 200) {
                                this.$message.success('添加分类成功')
                                this.addDialogVisible = false
                                this.fetchData()
                                this.fetchParentCategories() // 刷新父级分类选项
                            } else {
                                this.$message.error(response.data.msg || '添加分类失败')
                            }
                        })
                        .catch(error => {
                            console.error('添加分类出错:', error)
                            this.$message.error('添加分类失败')
                        })
                        .finally(() => {
                            this.loading = false
                        })
                }
            })
        },

        // 编辑分类 - 获取分类详情
        handleEdit(row) {
            this.loading = true;
            this.editDialogTitle = `编辑分类 - ${row.categoryName}`;

            // 根据level确定使用哪个ID
            const id = row.level === '一级' ? row.typeFirstId : row.typeSecondId;
            const level = row.level === '一级' ? 1 : 2;

            if (!id || !row.level) {
                this.$message.error('缺少必要的分类信息');
                this.loading = false;
                return;
            }

            console.log('正在请求分类详情，参数:', {
                id: id,
                level: row.level,
                fullUrl: `api/goods/queryGoodsTypeById/${id}/${level}`
            });

            // 发送请求获取分类详情
            this.$axios.get(`api/goods/queryGoodsTypeById/${id}/${level}`)
                .then(response => {
                    if (response.data.code === 200) {
                        const data = response.data.data;

                        if (!data) {
                            this.$message.error('未获取到分类详情数据');
                            return;
                        }

                        // 填充表单数据
                        this.editForm = {
                            id: id,
                            categoryName: row.level === '一级' ? (data.nameFirst || row.categoryName) : (data.nameSecond || row.categoryName),
                            level: row.level,
                            parentId: row.level === '二级' ? (data.typeFirstId || row.typeFirstId) : null,
                            typeFirstId: row.level === '二级' ? (data.typeFirstId || row.typeFirstId) : null,
                            status: data.status || row.status
                        };

                        this.editDialogVisible = true;
                    } else {
                        this.$message.error(response.data.msg || '获取分类详情失败');
                    }
                })
                .catch(error => {
                    console.error('获取分类详情出错:', error);
                    if (error.response) {
                        if (error.response.status === 400) {
                            this.$message.error('请求参数错误, 请检查分类ID和级别');
                        } else if (error.response.status === 404) {
                            this.$message.error('未找到对应的分类信息');
                        } else {
                            this.$message.error('获取分类详情失败');
                        }
                    } else {
                        this.$message.error('网络错误，请稍后重试');
                    }
                })
                .finally(() => {
                    this.loading = false;
                });
        },


        // 重置编辑表单
        resetEditForm() {
            this.$refs.editFormRef?.resetFields();
            this.editForm = {
                id: null,
                categoryName: '',
                level: '',
                parentId: null,
                typeFirstId: null,
                status: 1
            };
        },

        // 提交编辑表单
        submitEditForm() {
            this.$refs.editFormRef.validate(valid => {
                if (valid) {
                    const params = {
                        status: this.editForm.status,
                        level: this.editForm.level === '一级' ? 1 : 2,
                    };

                    // 如果是二级分类，添加父级分类ID
                    if (this.editForm.level === '二级') {
                        params.typeFirstId = this.editForm.parentId;
                        params.nameSecond = this.editForm.categoryName;
                        params.typeSecondId = this.editForm.id;
                    } else {
                        params.nameFirst = this.editForm.categoryName;
                        params.typeFirstId = this.editForm.id;
                    }

                    this.$axios.post('api/goods/updateGoodsType', params)
                        .then(response => {
                            if (response.data.code === 200) {
                                this.$message.success('更新分类成功');
                                this.editDialogVisible = false;
                                this.fetchData(); // 刷新列表
                            } else {
                                this.$message.error(response.data.msg || '更新分类失败');
                            }
                        });
                }
            });
        },

        // 修改分类状态
        handleStatusChange(row) {
            const newStatus = row.status === 1 ? 0 : 1;
            const action = newStatus === 1 ? '启用' : '停用';

            this.$confirm(`确定要${action}该分类吗?`, '提示', {
                type: 'warning'
            }).then(() => {
                // 构造请求参数
                const params = {
                    id: row.level === '一级' ? row.typeFirstId : row.typeSecondId,
                    level: row.level === '一级' ? 1 : 2,
                    status: newStatus,
                    typeSecondId: row.typeSecondId,
                    typeFirstId: row.typeFirstId
                };

                // 如果是二级分类，需要包含父分类ID
                if (row.level === '二级') {
                    params.typeFirstId = row.typeFirstId;
                }

                this.loading = true;
                this.$axios.post('api/goods/updateGoodsTypeStatus', params)
                    .then(response => {
                        if (response.data.code === 200) {
                            this.$message.success(`${action}分类成功`);
                            this.fetchData(); // 刷新列表
                        } else if(response.data.code === 4031){
                            this.$message.error(`拒绝${action}分类, 因为牵连到的下级分类仍在使用`);
                        } else if(response.data.code === 4032){
                            this.$message.error(`拒绝${action}分类, 因为牵连到的商品仍在使用`);
                        } else{
                            this.$message.error(response.data.msg || `${action}分类失败`);
                        }
                    })
                    .catch(error => {
                        console.error(`${action}分类出错:`, error);
                        this.$message.error(`${action}分类失败`);
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            }).catch(() => {
                this.$message.info('已取消操作');
            });
        }
    }
}
</script>

<style scoped>
.goods-type-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.table-card {
    margin-bottom: 20px;
}

.table-header {
    margin-bottom: 15px;
}

.pagination {
    margin-top: 15px;
    text-align: right;
}

.button-group {
    display: flex;
    justify-content: flex-end;
    padding-top: 5px;
}
</style>